<template>
  <div class="mobile-menu" @click="toggleSidebar">
    <svg viewBox="0 0 24 24" width="24" height="24">
      <path fill="currentColor" d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
    </svg>
  </div>

  <div class="chat-container">
    <div class="sidebar-overlay" 
         v-if="isSidebarOpen" 
         @click="toggleSidebar">
    </div>

    <div class="sidebar" :class="{ 'sidebar-open': isSidebarOpen }">
      <div class="logo">
        <h2>AI Chat</h2>
      </div>
      <button class="new-chat" @click="createNewChat">
        <span>+ 新建对话</span>
      </button>
      <div class="history">
        <div v-for="chat in chatHistory" 
             :key="chat.id" 
             :class="['history-item', { active: currentChatId === chat.id }]"
             @click="switchChat(chat.id)">
          <span class="chat-title">{{ chat.title || '新对话' }}</span>
          <button class="delete-btn" @click.stop="deleteChat(chat.id)">
            <svg viewBox="0 0 24 24" width="14" height="14">
              <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <div class="main-content">
      <div class="messages" ref="messageContainer">
        <div v-for="(message, index) in currentMessages" 
             :key="index" 
             :class="['message', message.role]">
          <div class="message-inner">
            <div class="avatar">
              {{ message.role === 'user' ? '👤' : '🤖' }}
            </div>
            <div class="content" v-if="message.role === 'assistant'" v-html="formatMessage(message.content)"></div>
            <div class="content" v-else>{{ message.content }}</div>
          </div>
          <div class="message-actions" v-if="message.role === 'assistant'">
            <button class="action-btn" @click="speakText(message.content)">
              <svg viewBox="0 0 24 24" width="16" height="16">
                <path fill="currentColor" d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
              </svg>
            </button>
            <button class="action-btn">
              <svg viewBox="0 0 24 24" width="16" height="16">
                <path fill="currentColor" d="M16 2v4h6v2h-2v14H4V8H2V6h6V2h8zm-2 2h-4v2h4V4zm0 4H6v12h12V8h-4z"/>
              </svg>
            </button>
          </div>
        </div>

        <!-- 添加加载状态提示 -->
        <div v-if="isLoading" class="loading-indicator">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
          <p>AI正在思考中...</p>
        </div>
      </div>

      <div class="input-area">
        <form @submit.prevent="sendMessage" class="chat-input">
          <input
            type="text"
            v-model="input"
            placeholder="输入您的问题..."
            :disabled="isLoading || isListening"
          />
          <button 
            type="button" 
            class="voice-btn"
            :class="{ 'listening': isListening }"
            @click="toggleVoiceInput"
            :disabled="isLoading"
          >
            <svg viewBox="0 0 24 24" width="20" height="20">
              <path fill="currentColor" d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.91-3c-.49 0-.9.36-.98.85C16.52 14.2 14.47 16 12 16s-4.52-1.8-4.93-4.15c-.08-.49-.49-.85-.98-.85-.61 0-1.09.54-1 1.14.49 3 2.89 5.35 5.91 5.78V20c0 .55.45 1 1 1s1-.45 1-1v-2.08c3.02-.43 5.42-2.78 5.91-5.78.1-.6-.39-1.14-1-1.14z"/>
            </svg>
          </button>
          <button type="submit" :disabled="isLoading || isListening || !input.trim()">
            <span class="button-content">
              <svg class="send-icon" viewBox="0 0 24 24">
                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
              </svg>
            </span>
          </button>
        </form>
        <div class="input-footer">
          通过输入框向AI助手提问
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css' // 可以选择其他主题
import { marked } from 'marked'

const chatHistory = ref([])
const currentChatId = ref(null)
const input = ref('')
const isLoading = ref(false)
const messageContainer = ref(null)
const isSidebarOpen = ref(false)
const isListening = ref(false)
const isSpeaking = ref(false)
let recognition = null
let speechSynthesis = window.speechSynthesis
let speechUtterance = null

// 生成唯一ID
const generateId = () => Date.now().toString(36) + Math.random().toString(36).substr(2)

// 创建新对话
const createNewChat = () => {
  const newChat = {
    id: generateId(),
    title: '新对话',
    messages: []
  }
  chatHistory.value.unshift(newChat)
  currentChatId.value = newChat.id
}

// 删除对话
const deleteChat = (chatId) => {
  const index = chatHistory.value.findIndex(chat => chat.id === chatId)
  if (index !== -1) {
    chatHistory.value.splice(index, 1)
    if (chatId === currentChatId.value) {
      currentChatId.value = chatHistory.value[0]?.id || null
    }
  }
}

// 切换对话
const switchChat = (chatId) => {
  currentChatId.value = chatId
  if (window.innerWidth <= 768) {
    isSidebarOpen.value = false
  }
}

// 获取当前对话的消息
const currentMessages = computed(() => {
  const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
  return currentChat?.messages || []
})

// 发送消息
const sendMessage = async () => {
  if (!input.value.trim()) return
  if (!currentChatId.value) {
    createNewChat()
  }

  isLoading.value = true
  const userMessage = { role: 'user', content: input.value }
  
  // 找到当前对话并添加消息
  const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
  if (currentChat) {
    currentChat.messages.push(userMessage)
    
    // 如果是第一条消息，将其设置为对话标题
    if (currentChat.messages.length === 1) {
      currentChat.title = input.value.slice(0, 20) + (input.value.length > 20 ? '...' : '')
    }
  }

  try {
    const response = await fetch('https://api.deepseek.com/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: [...currentMessages.value, userMessage],
        stream: false
      })
    })

    const data = await response.json()
    if (currentChat) {
      const assistantMessage = data.choices[0].message
      currentChat.messages.push(assistantMessage)
      // 对AI回复进行语音播放
      speakText(assistantMessage.content)
    }
  } catch (error) {
    console.error('Error:', error)
  } finally {
    isLoading.value = false
    input.value = ''
  }
}

// 初始化创建一个对话
if (chatHistory.value.length === 0) {
  createNewChat()
}

const toggleSidebar = () => {
  isSidebarOpen.value = !isSidebarOpen.value
}

// 配置 marked
marked.setOptions({
  highlight: function (code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true
})

// 格式化消息内容
const formatMessage = (content) => {
  return marked(content)
}

// 初始化语音识别
const initSpeechRecognition = () => {
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
  if (SpeechRecognition) {
    recognition = new SpeechRecognition()
    recognition.lang = 'zh-CN'
    recognition.continuous = false
    recognition.interimResults = false

    recognition.onresult = (event) => {
      const transcript = event.results[0][0].transcript
      input.value = transcript
      isListening.value = false
    }

    recognition.onerror = (event) => {
      console.error('语音识别错误:', event.error)
      isListening.value = false
    }

    recognition.onend = () => {
      isListening.value = false
    }
  }
}

// 切换语音输入
const toggleVoiceInput = () => {
  if (!recognition) {
    initSpeechRecognition()
  }
  
  if (!recognition) {
    alert('您的浏览器不支持语音识别功能')
    return
  }

  if (isListening.value) {
    recognition.stop()
  } else {
    input.value = ''
    recognition.start()
    isListening.value = true
  }
}

// 初始化语音合成
const initSpeechSynthesis = () => {
  if (!speechSynthesis) {
    console.error('浏览器不支持语音合成')
    return
  }
  
  // 获取中文语音
  const voices = speechSynthesis.getVoices()
  const chineseVoice = voices.find(voice => voice.lang.includes('zh'))
  
  speechUtterance = new SpeechSynthesisUtterance()
  speechUtterance.voice = chineseVoice
  speechUtterance.lang = 'zh-CN'
  speechUtterance.rate = 1
  speechUtterance.pitch = 1
  
  speechUtterance.onend = () => {
    isSpeaking.value = false
  }
  
  speechUtterance.onerror = (event) => {
    console.error('语音合成错误:', event)
    isSpeaking.value = false
  }
}

// 文字转语音
const speakText = (text) => {
  if (!speechSynthesis) {
    initSpeechSynthesis()
  }
  
  if (!speechSynthesis) {
    return
  }
  
  // 如果正在播放,先停止
  if (isSpeaking.value) {
    speechSynthesis.cancel()
  }
  
  // 去除markdown标记等特殊字符
  const cleanText = text.replace(/[#*`]/g, '').replace(/\n/g, ' ')
  speechUtterance.text = cleanText
  speechSynthesis.speak(speechUtterance)
  isSpeaking.value = true
}

// 在组件卸载时清理
onUnmounted(() => {
  if (recognition) {
    recognition.stop()
  }
  if (speechSynthesis) {
    speechSynthesis.cancel()
  }
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background: #f9fafb;
}

.sidebar {
  width: 280px;
  background: #f3f4f6;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.logo {
  padding: 12px 0;
  color: #374151;
}

.new-chat {
  background: #10b981;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  margin: 8px 0;
  transition: background-color 0.2s;
}

.new-chat:hover {
  background: #059669;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin: 20px 0;
}

.message-inner {
  display: flex;
  align-items: flex-start;
  max-width: 900px;
  margin: 0 auto;
}

.message.assistant {
  background: #f3f4f6;
}

.message.assistant .message-inner {
  padding: 20px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2em;
  margin-right: 16px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.content {
  flex: 1;
  line-height: 1.6;
  font-size: 15px;
  color: #374151;
}

.message-actions {
  max-width: 900px;
  margin: 8px auto 0;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding: 0 20px;
}

.action-btn {
  position: relative;
}

.action-btn:hover::after {
  content: "播放语音";
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  margin-bottom: 4px;
}

.action-btn:last-child:hover::after {
  content: "复制文本";
}

.input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #e5e7eb;
}

.chat-input {
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  gap: 12px;
  background: white;
}

input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f9fafb;
}

input:focus {
  outline: none;
  border-color: #10b981;
  background: white;
}

button {
  padding: 8px;
  color: #6b7280;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  border-color: #10b981;
  color: #10b981;
}

.send-icon {
  width: 20px;
  height: 20px;
  fill: currentColor;
}

.input-footer {
  max-width: 900px;
  margin: 8px auto 0;
  text-align: center;
  color: #6b7280;
  font-size: 12px;
}

/* 滚动条样式 */
.messages::-webkit-scrollbar {
  width: 4px;
}

.messages::-webkit-scrollbar-track {
  background: transparent;
}

.messages::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 4px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.history {
  flex: 1;
  overflow-y: auto;
  margin-top: 12px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 6px;
  cursor: pointer;
  color: #374151;
  transition: background-color 0.2s;
}

.history-item:hover {
  background: #e5e7eb;
}

.history-item.active {
  background: #e5e7eb;
}

.chat-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.delete-btn {
  padding: 4px;
  border: none;
  background: transparent;
  color: #6b7280;
  opacity: 0;
  transition: opacity 0.2s;
}

.history-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  color: #ef4444;
}

/* 修改滚动条样式 */
.history::-webkit-scrollbar {
  width: 4px;
}

.history::-webkit-scrollbar-track {
  background: transparent;
}

.history::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 4px;
}

.history::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

/* 移动端菜单按钮 */
.mobile-menu {
  display: none;
  position: fixed;
  top: 12px;
  left: 12px;
  z-index: 1000;
  padding: 8px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  cursor: pointer;
}

/* 遮罩层 */
.sidebar-overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .mobile-menu {
    display: block;
  }

  .sidebar-overlay.sidebar-open {
    display: block;
  }

  .chat-container {
    position: relative;
  }

  .sidebar {
    position: fixed;
    left: -280px;
    top: 0;
    bottom: 0;
    z-index: 1000;
    transition: left 0.3s ease;
  }

  .sidebar.sidebar-open {
    left: 0;
  }

  .main-content {
    margin-left: 0;
    padding-top: 60px;
  }

  .message-inner {
    padding: 12px !important;
  }

  .messages {
    padding: 10px;
  }

  .input-area {
    padding: 12px;
  }

  .chat-input {
    gap: 8px;
  }

  input {
    padding: 10px;
  }

  .message-actions {
    padding: 0 12px;
  }

  .content {
    font-size: 14px;
  }

  .avatar {
    width: 28px;
    height: 28px;
    font-size: 1em;
    margin-right: 12px;
  }

  .input-footer {
    font-size: 11px;
  }

  .voice-btn {
    padding: 6px;
  }
  
  .voice-btn svg {
    width: 18px;
    height: 18px;
  }
}

/* 较小屏幕的额外优化 */
@media (max-width: 480px) {
  .main-content {
    padding-top: 50px;
  }

  .message-inner {
    padding: 10px !important;
  }

  .input-area {
    padding: 10px;
  }

  .messages {
    padding: 8px;
  }

  .content {
    font-size: 13px;
  }

  .avatar {
    width: 24px;
    height: 24px;
    margin-right: 8px;
  }
}

/* 确保在大屏幕上sidebar始终可见 */
@media (min-width: 769px) {
  .sidebar {
    position: sticky !important;
    left: 0 !important;
  }

  .mobile-menu,
  .sidebar-overlay {
    display: none !important;
  }
}

/* 添加代码块样式 */
.content :deep(pre) {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 12px 0;
  border: 1px solid #e5e7eb;
}

.content :deep(code) {
  font-family: 'Fira Code', monospace;
  font-size: 14px;
}

.content :deep(p) {
  margin: 8px 0;
}

/* 行内代码样式 */
.content :deep(:not(pre) > code) {
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  color: #ef4444;
}

/* 代码块头部样式 */
.content :deep(pre) {
  position: relative;
}

.content :deep(pre)::before {
  content: attr(class);
  position: absolute;
  top: 0;
  right: 0;
  padding: 4px 8px;
  font-size: 12px;
  color: #6b7280;
  background: #f3f4f6;
  border-bottom-left-radius: 6px;
  border-top-right-radius: 6px;
}

/* 添加加载状态提示 */
.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: white;
  border-top: 1px solid #e5e7eb;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  animation: blink 1.4s infinite;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6b7280;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 添加语音按钮样式 */
.voice-btn {
  padding: 8px;
  color: #6b7280;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-btn:hover:not(:disabled) {
  border-color: #10b981;
  color: #10b981;
}

.voice-btn.listening {
  background: #10b981;
  color: white;
  border-color: #10b981;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(16, 185, 129, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
  }
}
</style> 